package com.ruoyi.project.newhope.transfer.controller;

import com.ruoyi.framework.web.controller.BaseController;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.project.newhope.data.domain.NewHopeData;
import com.ruoyi.project.newhope.data.service.INewHopeDataService;
import com.ruoyi.project.newhope.device.domain.NewHopeInfraredDevice;
import com.ruoyi.project.newhope.device.service.INewHopeInfraredDeviceService;
import com.ruoyi.project.newhope.material.domain.NewHopeMaterial;
import com.ruoyi.project.newhope.material.mapper.NewHopeMaterialMapper;
import com.ruoyi.project.newhope.transfer.domain.TransferOracleEBSModel;
import com.ruoyi.project.newhope.transfer.util.OracleEBSUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@Controller
@RequestMapping("/api/newhope/transfer")
public class TransferController extends BaseController {

    @Autowired
    private INewHopeDataService newHopeInfraredDevice;
    @Autowired
    private INewHopeInfraredDeviceService newHopeInfraredDeviceService;
    @Autowired
    private NewHopeMaterialMapper newHopeMaterialMapper;

    /**
     * 上传数据
     */
    @PostMapping("/uploadData")
    @ResponseBody
    public AjaxResult uploadData(@RequestBody NewHopeData newHopeData) {
        List<NewHopeData> list = newHopeInfraredDevice.selectNewHopeDataList(newHopeData);
        if (CollectionUtils.isEmpty(list)) {
            return AjaxResult.error("未查询符合当前上传条件的数据");
        }
        //传输结果集合
        List<TransferOracleEBSModel> ebsModels = new ArrayList<>();

        //获取检测点对象得到掐头去尾设置
        NewHopeData temp = list.get(0);
        NewHopeInfraredDevice device = newHopeInfraredDeviceService.selectNewHopeInfraredDeviceById(temp.getDeviceId());
        Integer headDiscard = (device != null && device.getHeadDiscard() != null) ? device.getHeadDiscard() : 0 ;
        Integer endDiscard = (device != null && device.getHeadDiscard() != null) ? device.getEndDiscard() : 0 ;;

        Map<String, List<NewHopeData>> groupData = list.stream().collect(Collectors.groupingBy(NewHopeData::getInspectionName));
        groupData.forEach((key, subGroupData) -> {
            //根据materialCode+batchNum分组
            Map<String, List<NewHopeData>> collect = subGroupData.stream().collect(Collectors.groupingBy(NewHopeData::getBatchNum));
            for (Map.Entry<String, List<NewHopeData>> entry : collect.entrySet()) {
                List<NewHopeData> dataList = entry.getValue();
                if (dataList == null || dataList.size() == 0) {
                    continue;
                }
                if (dataList.size() >= headDiscard && headDiscard > 0) {
                    dataList = dataList.subList(headDiscard, dataList.size());
                }
                if (dataList.size() >= endDiscard && endDiscard > 0) {
                    dataList = dataList.subList(0, dataList.size() - endDiscard);
                }
                if (dataList.size() == 0) {
                    continue;
                }
                double avgInspectionValue = dataList.stream().mapToDouble(NewHopeData::getInspectionValue).average().getAsDouble();
                NewHopeData hopeData = dataList.get(0);
                //根据物料编码查询映射编码
                NewHopeMaterial material = newHopeMaterialMapper.selectByMaterialCode(hopeData.getMaterialCode());
                if (material != null) {
                    TransferOracleEBSModel model = new TransferOracleEBSModel(material.getMappingCode(), newHopeData.getBatchNum(), hopeData.getInspectionCode(), avgInspectionValue);
                    ebsModels.add(model);
                }
            }
        });

        //上传 oracleEBS
        try {
            if (ebsModels.size() == 0) {
                return AjaxResult.error("当前上传数据经过条件筛选、掐头去尾后不存在有效数据");
            }
            List<TransferOracleEBSModel> targetEbsModels = new ArrayList<>();
            Map<String, List<TransferOracleEBSModel>> collect = ebsModels.stream().collect(Collectors.groupingBy(TransferOracleEBSModel::getInspectionCode));
            collect.forEach((key, modelList) -> {
                TransferOracleEBSModel model1 = modelList.get(0);
                double avgInspectionValue = modelList.stream().mapToDouble(TransferOracleEBSModel::getInspectionValue).average().getAsDouble();
                TransferOracleEBSModel model = new TransferOracleEBSModel(model1.getMaterialCode(), newHopeData.getBatchNum(), model1.getInspectionCode(), avgInspectionValue);
                targetEbsModels.add(model);
            });
            return OracleEBSUtil.transferDataToEBS(targetEbsModels);
        } catch (Exception ex) {
            ex.printStackTrace();
            log.info("上传数据至 oracleEBS 失败 ex={}", ex.getMessage(), ex);
            return AjaxResult.error("上传数据至 oracleEBS 失败");
        }
    }
}
